# @time     :2021/12/31
# @Author   :Simple
# @FileName :main_page
import json

from selenium import webdriver
from selenium.webdriver.common.by import By

from common.element import GetElement
from qyex.page.admin_page import AdminPage
from qyex.page.login_page.login_page import LoginPage
from qyex.page.register_page.register_page import RegisterPage


class MainPage:
    """
    企业微信主页
    """
    login_btn = GetElement(xpath="//*[@class='index_top_operation_loginBtn']", describe="登录按钮", wait=True)
    register_btn = GetElement(xpath="//*[@class='index_head_info_pCDownloadBtn']", describe="注册按钮", wait=True)

    def __init__(self, login_flag=True):
        """
        企业微信主页
        :param login_flag: 是否已登录
        """
        # 关闭浏览器，再复用浏览器，
        # 执行命令： chrome --remote-debugging-port=9222
        # 手动登录后再执行测试用例
        if login_flag:
            chrome_arg = webdriver.ChromeOptions()
            chrome_arg.debugger_address = '127.0.0.1:9222'
            self.driver = webdriver.Chrome(options=chrome_arg)
        else:
            self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(5)
        self.driver.get("https://work.weixin.qq.com/")
        self.vars = {}

    def goto_login(self):
        """
        登录
        :return:
        """
        self.login_btn.click()
        return LoginPage(self.driver)

    def goto_admin(self):
        """
        已经手动登录，点击登录按钮直接进入首页
        :return:
        """
        self.get_cookies("../data/cookie.txt")  # 保存cookies到文件中
        self.login_btn.click()
        return AdminPage(self.driver)

    def goto_register(self):
        """
        注册
        :return:
        """
        self.register_btn.click()
        return RegisterPage(self.driver)

    def goto_login_by_cookies(self, file):
        """
        未登录，读取cookies后使用cookie登录
        :return:
        """
        # 读取cookie
        with open(file, 'r', encoding="utf-8") as f:
            # 序列化
            cookies = json.load(f)
        for i in cookies:
            self.driver.add_cookie(i)
        self.driver.refresh()
        return self.goto_login()

    def get_cookies(self, file):
        """
        复用已登录的浏览器，获取cookies存入文件
        :return:
        """
        # 先复用浏览器登录后再存入cookie
        cookies = self.driver.get_cookies()
        with open(file, "w", encoding="utf-8") as f:
            json.dump(cookies, f)

